<template>
  <div class="customer-detail-box">
    <el-card class="box-card" style="margin-bottom:10px">
      <div slot="header" class="clearfix">
        <span>线索信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">线索ID：{{ clue.id }}</el-col>
        <el-col :span="8">客户姓名：{{ clue.name }}</el-col>
        <el-col :span="8">客户性别：{{sexFormat(clue.sex)}}</el-col>
      </el-row>
        <el-row :gutter="20">
        <el-col :span="8">客户年龄：{{ clue.age }}</el-col>
        <el-col :span="8">客户微信：{{ clue.weixin }}</el-col>
        <el-col :span="8">客户QQ：  {{clue.qq}}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">手机号：{{clue.phone}}</el-col>
        <el-col :span="8">创建时间：{{ clue.createTime }}</el-col>
        <el-col :span="8">线索分配：{{ clue.createBy }}</el-col>
      </el-row>
      <el-row :gutter="20"> 
        <el-col :span="8">线索归属：{{ clue.ownerName }}</el-col>
        <el-col :span="8">归属时间：{{ clue.ownerTime }}</el-col>
        <el-col :span="8">渠道来源：{{channelOptionsFormat(clue.channel)}}</el-col> 
      </el-row>
      <el-row :gutter="20">
        <el-col>活动信息：{{ clue.activityInfo }}</el-col>
      </el-row>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>跟进记录</span>
        <el-button style="float: right;" type="danger" @click="handleReport()">伪线索上报</el-button>
        <el-button style="float: right;margin-right:10px" type="success" @click="handleChangeBusiness()">转商机</el-button>
        <el-button style="float: right;" type="primary" @click="handleAdd">新增跟进记录</el-button>
      </div>
      <el-table :data="pageData.data" style="width: 100%" border>
        <el-table-column prop="level" label="意向等级">
          <template slot-scope="scope">
            {{levelFormat(scope.row.level)}}
          </template>
        </el-table-column>
        <el-table-column prop="subject" label="意向学科">
          <template slot-scope="scope">
            {{subjectFormat(scope.row.subject)}}
          </template>
        </el-table-column>
        <el-table-column prop="record" label="跟进记录"></el-table-column>
        <el-table-column prop="createBy" label="跟进人"></el-table-column>
        <el-table-column prop="createTime" label="跟进时间"></el-table-column>
        <el-table-column prop="nextTime" label="下次跟进时间"></el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.totalCount">
      </el-pagination>
    </el-card>

    <el-dialog title="添加跟进" :visible.sync="dialogSaveRecordVisible">
      <el-form ref="saveForm" class="cus-search-box cus-form-box" :model="saveForm" :rules="rules" label-width="110px" inline>
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="saveForm.name" placeholder="请输入客户姓名"  />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="saveForm.sex" >
            <el-radio
              v-for="dict in sexOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)">
              {{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="saveForm.age" :precision="0" :min="1" 
          :max="99" :step="1" placeholder="请输入年龄" controls-position="right" style="width:205px"/>
        </el-form-item>
        <el-form-item label="微信号" prop="weixin">
          <el-input v-model="saveForm.weixin" placeholder="请输入微信号" maxlength="20"  />
        </el-form-item>
        <el-form-item label="qq" prop="qq">
          <el-input v-model="saveForm.qq" placeholder="请输入qq" maxlength="20"/>
        </el-form-item>
        <el-form-item class="wp-100" label="意向学科" prop="subject">
          <el-select v-model="saveForm.subject" placeholder="请选择意向学科" clearable >
            <el-option
              v-for="dict in subjectOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item class="wp-100" label="意向等级" prop="level">
          <el-radio-group v-model="saveForm.level" >
            <el-radio
              v-for="dict in levelOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)">
              {{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item class="wp-100" label="跟进记录" prop="record">
          <el-input v-model="saveForm.record" type="textarea" :rows="4" 
              show-word-limit placeholder="请输入跟进记录" maxlength="255" style="width:550px"/>
        </el-form-item>
        <el-form-item class="wp-100" label="下次跟进时间" prop="nextTime">
          <el-date-picker
            v-model="saveForm.nextTime"
            clearable
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择下次跟进时间"
            default-time="12:00:00"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSaveRecordVisible = false">取 消</el-button>
        <el-button type="primary" @click="doSave">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="伪线索上报" :visible.sync="dialogReportVisible">
      <el-form ref="reportForm" class="cus-search-box cus-dialog-form-box" :model="reportForm" :rules="reportRules" label-width="90px">
        <el-form-item class="wp-100" label="原因" prop="falseReason">
          <el-select v-model="reportForm.falseReason" placeholder="请选择原因">
            <el-option
              v-for="dict in falseReasonOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="wp-100" label="备注" prop="record">
          <el-input v-model="reportForm.record" type="textarea" maxlength="255" :rows="4" show-word-limit placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogReportVisible = false">取 消</el-button>
        <el-button type="primary" @click="doReportSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    const validDateTime = (rule, value, callback) => {
      if ((new Date(value)).getTime() < (new Date()).getTime()) {
        return callback(new Error('下次跟进时间不能小于当前时间'))
      } else {
        callback()
      }
    };
    return {
      // 详情数据
      clue: {},
      //查询的数据模型
      searchForm: {
        //过滤条件
        clueId: null,
        //分页条件
        pageNo: 1,
        pageSize: 5,
      },
      //新增跟进记录对话框显示标记
      dialogSaveRecordVisible:false,
      //伪线索上报对话框显示标记
      dialogReportVisible:false,
      // 性别字典
      sexOptions: [],
      // 意向等级字典
      levelOptions: [],
      // 意向学科字典
      subjectOptions: [],
      //渠道来源
      channelOptions: [],
      //伪线索
      falseReasonOptions: [],
      //跟进记录
      pageData: {
        data: [], // 分页数据
        pageNo: 1, // 当前页
        pageSize: 5, // 一页的大小
        totalCount: 0, // 总数据量
        totalPageCount: 0, // 总页数
      },
      //新增跟进记录的数据模型
      saveForm: {
        clueId:null,
        name:null,
        sex:0,
        age:null,
        weixin:null,
        qq:null,
        subject:null,
        level:null,
        record:null,
        nextTime:null,
      },
      //新增跟进记录的表单验证规则
      rules:{
        name: [
          { required: true, message: '客户姓名不能为空', trigger: 'blur' },
        ],
        level: [
          { required: true, message: '意向等级不能为空', trigger: 'change' }
        ],
        subject: [
          { required: true, message: '意向学科不能为空', trigger: 'change' }
        ],
        record: [
          { required: true, message: '跟进记录不能为空', trigger: 'blur' }
        ],
        nextTime: [
          { required: true, message: '下次跟进时间不能为空', trigger: 'blur' },
          { validator: validDateTime, message: '下次跟进时间不能小于当前时间' }
        ],
        weixin: [
          { required: true, message: '微信号不能为空', trigger: 'blur' },
        ],
        qq: [
          { required: true, message: 'QQ号不能为空', trigger: 'blur' },
        ]
      },
      // 上报伪线索表单参数
      reportForm: {
        clueId: null,
        falseReason: null,
        record: null
      },
      // 上报伪线索表单验证规则
      reportRules:{
         falseReason: [
          { required: true, message: '原因不能为空', trigger: 'blur' }
        ]
      },
    }
  },
  created () {
    this.searchForm.clueId = this.$route.query.id
    //查询页面所需的数据字典
    this.getDicList()
    //查询线索信息
    this.getInfo()
    //查询跟进记录
    this.getRecordList()
  },
  methods: {
    //查询线索详情
    getInfo () {
      this.$axios.get("/api/tb/clue/view/"+this.searchForm.clueId)
        .then((res) => {
          if (res.data.code == 200) {
            this.clue = res.data.data
            //设置客户详情信息
            this.saveForm.name = this.clue.name
            this.saveForm.sex = this.clue.sex
            this.saveForm.age = this.clue.age
            this.saveForm.weixin = this.clue.weixin
            this.saveForm.qq = this.clue.qq
          } else {
            this.$message.error(res.data.msg);
          }
        })
    },
    //查询线索跟进记录
    getRecordList () {
      this.$axios.get("/api/tb/clueRecord/list", {params:this.searchForm})
        .then((res) => {
          if (res.data.code == 200) {
            this.pageData.pageNo = res.data.data.current;
            this.pageData.pageSize = res.data.data.size;
            this.pageData.totalCount = res.data.data.total;
            this.pageData.totalPageCount = res.data.data.pages;
            this.pageData.data = res.data.data.records;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //改变每页显示的条数
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getRecordList();
    },
    //改变当前的页码数
    handleCurrentChange(val) {
      this.searchForm.pageNo = val;
      this.getRecordList();
    },
    //添加
    handleAdd() {
      //1.清空模型数据
      this.reset();
      //2.显示对话框
      this.dialogSaveRecordVisible = true;
    },
    //保存
    doSave() {
      this.$refs["saveForm"].validate((vali) => {
        if (vali) {
          this.saveForm.clueId = this.clue.id;
          //发送ajax请求
          this.$axios.post("/api/tb/clueRecord/save", this.saveForm)
            .then((res) => {
              if (res.data.code == 200) {
                //1.关闭对话框
                this.dialogSaveRecordVisible = false;
                //2.友好提示
                this.$message.success(res.data.msg);
                //3.刷新表格
                this.getRecordList();
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
            })
        }
      });
    },
    // 上报
    handleReport () {
      //显示对话框
      this.dialogReportVisible=true;
    },
    //上报伪线索
    doReportSave() {
      this.$refs["reportForm"].validate((vali) => {
        if (vali) {
          this.reportForm.clueId = this.clue.id;
          //发送ajax请求
          this.$axios.put("/api/tb/clue/falseClue", this.reportForm)
            .then((res) => {
              if (res.data.code == 200) {
                //1.关闭对话框
                this.dialogReportVisible = false;
                //2.友好提示
                this.$message.success(res.data.msg);
                //3.刷新表格
                this.$router.back();
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
            })
        }
      });
    },
    // 转商机
    handleChangeBusiness() {
      this.$confirm('确定转为商机吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //1.发送ajax请求
        this.$axios.put("/api/tb/clue/changeBusiness/"+ this.clue.id)
          .then((res)=>{
            if (res.data.code == 200) {
              //1.友好提示
              this.$message.success(res.data.msg);
              //2.刷新表格
              this.$router.back();
            } else {
              //1.友好提示
              this.$message.error(res.data.msg);
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消转为商机'
        });          
      });
    },
    //清空新增表单数据
    reset () {
      this.saveForm.level = null
      this.saveForm.subject = null
      this.saveForm.record = null
      this.saveForm.nextTime = null
    },
    // 回显数据字典
    selectDictLabel(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].dictValue == ('' + value)) {
          actions.push(datas[key].dictLabel);
          return true;
        }
      })
      return actions.join('');
    },
    // 性能字典翻译
    sexFormat (val) {
      return this.selectDictLabel(this.sexOptions, val)
    },
    // 意向等级字典翻译
    levelFormat (val) {
      return this.selectDictLabel(this.levelOptions, val)
    },
    // 意向学科字典翻译
    subjectFormat (val) {
      return this.selectDictLabel(this.subjectOptions, val)
    },
    // 渠道来源字典翻译
    channelOptionsFormat (val) {
      return this.selectDictLabel(this.channelOptions, val)
    },
    // 伪线索字典翻译
    reasonsOptionsFormat (val) {
      return this.selectDictLabel(this.falseReasonOptions, val)
    },
    //查询数据字典
    getDicList () {
      this.$axios.get("/api/sys/dictData/optionselect/sys_user_sex")
        .then((res) => {
          if (res.data.code == 200) {
            this.sexOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
      this.$axios.get("/api/sys/dictData/optionselect/clues_level")
        .then((res) => {
          if (res.data.code == 200) {
            this.levelOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
      this.$axios.get("/api/sys/dictData/optionselect/course_subject")
        .then((res) => {
          if (res.data.code == 200) {
            this.subjectOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
      this.$axios.get("/api/sys/dictData/optionselect/clues_item")
        .then((res) => {
          if (res.data.code == 200) {
            this.channelOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
      this.$axios.get("/api/sys/dictData/optionselect/reasons_for_reporting")
        .then((res) => {
          if (res.data.code == 200) {
            this.falseReasonOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
    },
  }
}
</script>
<style scoped>
   .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
</style>
